package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.subject.oneSubject;
import com.atguigu.eduservice.entity.subject.twoSubject;
import com.atguigu.eduservice.excel.SubjectData;
import com.atguigu.eduservice.excel.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionHandler.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-02-05
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Override
    public List<oneSubject> getAllOneTwoSubject() {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        // 一级分类
        List<EduSubject> eduSubjectList = this.list(queryWrapper);

        QueryWrapper<EduSubject> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ne("parent_id", 0);
        // 二级分类
        List<EduSubject> eduSubjectList1 = this.list(queryWrapper1);

        List<oneSubject> list = new ArrayList<>();
        // 空间换时间
        HashMap<String, oneSubject> map = new HashMap<>();
        for (EduSubject eduSubject : eduSubjectList) {
            oneSubject oneSubject = new oneSubject();
            BeanUtils.copyProperties(eduSubject, oneSubject);
            map.put(oneSubject.getId(), oneSubject);
            list.add(oneSubject);
        }
        // 将二级分类，添加到对应的一级分类上
        for (EduSubject subject : eduSubjectList1) {
            oneSubject oneSubject = map.get(subject.getParentId());
            twoSubject twoSubject = new twoSubject();
            BeanUtils.copyProperties(subject, twoSubject);
            oneSubject.getChildren().add(twoSubject);
        }
        return list;
    }

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(20002, "添加课程分类失败");
        }

        EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
    }
}
